package com.zoe.onelink.actuate.check;

import com.zoe.onelink.plugin.check.AbstractEnvironmentChecker;
import com.zoe.onelink.plugin.check.model.PropertyCheckResult;
import com.zoe.onelink.util.StrUtil;
import org.springframework.boot.web.server.Shutdown;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2022</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2022-09-20
 */
public class ActuatorEnvironmentChecker extends AbstractEnvironmentChecker {

    @Override
    public List<PropertyCheckResult<?>> doCheck() {
        List<PropertyCheckResult<?>> propertyCheckResults = new ArrayList<>();
        String shutdownPropKey = "server.shutdown";
        Shutdown shutdownType = this.getProperty(shutdownPropKey, Shutdown.class, Shutdown.IMMEDIATE);
        String shutdownEndpointKey = "management.endpoint.shutdown.enabled";
        Boolean shutdownEndpointEnabled = this.getProperty(shutdownEndpointKey, Boolean.class, false);
        PropertyCheckResult<Shutdown> shutdownPropCheckResult = new PropertyCheckResult<Shutdown>()
                .setPropKey(shutdownPropKey)
                .setPropValue(shutdownType)
                .setLevel(PropertyCheckResult.Level.DANGER);
        boolean isGracefulShutdown = shutdownType == Shutdown.GRACEFUL;
        if (isGracefulShutdown && !shutdownEndpointEnabled) {
            String msg = StrUtil.format("当前服务已开启优雅关机[{}={}],但优雅关机端点[{}={}]未开启,可能导致优雅关机功能失效",
                    shutdownPropKey, Shutdown.GRACEFUL, shutdownEndpointKey, false);
            shutdownPropCheckResult.setMessage(msg);
            propertyCheckResults.add(shutdownPropCheckResult);
        } else if (!isGracefulShutdown && shutdownEndpointEnabled) {
            String msg = StrUtil.format("当前服务未开启优雅关机[{}={}],但启用了优雅关机端点[{}={}],可能导致优雅关机功能失效",
                    shutdownPropKey, shutdownType, shutdownEndpointKey, true);
            shutdownPropCheckResult.setMessage(msg);
            propertyCheckResults.add(shutdownPropCheckResult);
        }
        return propertyCheckResults;
    }
}
